<template>
    <div class=" population-page u-f">
      <div class="flex-1 u-f-ajc">
        <div class="p-20">
          <h2 class="tac fz-45" style="font-family: 'Xingkai', 'Xingkai SC', cursive;">唐朝人物姓氏图</h2>
          <p class="fz-22" style="font-family: 'Xingkai', 'Xingkai SC', cursive;">
              本图以<span style="font-size: 35px; color: #95302e;font-weight: bold;">气泡图</span>形式展示唐代历史人物姓氏的数量分布。<br><br>
              通过对唐朝人物的姓氏进行统计，找出数量排名<span style="font-size: 35px; color: #95302e;font-weight: bold;">前一百</span>的姓氏。每个气泡代表一个姓氏，其大小与该姓氏人数成正比，直观呈现了各姓氏的频率。<br><br>
              其中，“<span style="font-size: 35px; color: #95302e;font-weight: bold;">李</span>”姓气泡最为突出，表明在唐朝“李”
              姓是最为常见的姓氏之一，其人数相对较多。除此之外，还有一些其他常见的大姓氏，如
              “<span style="font-size: 35px; color: #95302e;font-weight: bold;">王</span>”、
              “<span style="font-size: 35px; color: #95302e;font-weight: bold;">張</span>”、“<span style="font-size: 35px; color: #95302e;font-weight: bold;">陳</span>”等，在唐朝社会也有着显著的存在。<br><br>
              可以通过悬浮、拖拽的方式进行交互，将鼠标悬浮在气泡处，可以得到对应姓氏的数量。
          </p>
        </div>
      </div>
      <div class="flex-1 h100 chart" ref="chart"></div>
    </div>
</template>
<script>
import * as echarts from 'echarts'

import { poetCountSurname } from '@/api/poet-api'
export default {
  name: 'PopulationSurname',
  data() {
    return {
      dataList: []
    }
  },
  mounted(){
    poetCountSurname({size: 100}).then(res => {
      if (res.code === '200') {        
        this.dataList = res.data
        this.initChart()
      }
    })
    
  },
  methods: {
    generateNonOverlappingData(bubbleData, areaSize = 100) {
      const points = [];
      return bubbleData.map(item => {      
        
        let x, y, attempts = 0;
        const radius = item.value * 2; // 气泡半径（根据 symbolSize 计算）

        // 最大尝试次数避免死循环
        while (attempts < 100) {
          x = Math.random() * areaSize;
          y = Math.random() * areaSize;
          
          // 检测与已存在点是否碰撞
          const isOverlap = points.some(p => {
            const dx = p.x - x;
            const dy = p.y - y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            return distance < (p.radius + radius);
          });

          if (!isOverlap) break; // 无碰撞则退出循环
          attempts++;
        }
        points.push({ x, y, radius }); // 记录已放置点
        return {'x': x, 'y': y, 'radius': radius, 'data': item};
      });
    },
    initChart(){
      const chartInstance = echarts.init(this.$refs.chart)

      // const data = [ 
      //   {surname: '李', countSurname: 3161},
      //   {surname: '王', countSurname: 2221},
      //   {surname: '張', countSurname: 2126},
      //   {surname: '陳', countSurname: 4465},
      //   {surname: '劉', countSurname: 3332}
      // ]
      const data = this.dataList.map(e => {
        return {
          'surname': e.surname,
          'countSurname': e.number
        }
      })

      let maxVal = 0;
      const bubbleData = data.map(item => {
        maxVal = Math.max(maxVal, item.countSurname)
        
        return {
          name: item.surname,
          value: item.countSurname,
          itemStyle: {
            color: '#a04c3b'
          }
        }
      });

      const option = {
        title: {
        },
        tooltip: {
          trigger: 'item',
          axisPointer: {
            show: false
          },
          formatter: function(val) {            
            return `${val.data.data.value}`
          }
        },
        xAxis: {
          min: 0,
          max: 100,
          type: 'value',
          scale: true,
          show: false,
          axisLine: { show: false }, // 双重保险隐藏轴线
          axisTick: { show: false }, // 隐藏刻度线
          axisLabel: { show: false },
          axisPointer: {
            show: false // 仅禁用 X 轴指示线‌:ml-citation{ref="4,7" data="citationList"}
          }
        },
        yAxis: {
          min: 0,
          max: 100,
          type: 'value',
          scale: true,
          show: false,
          axisLine: { show: false }, // 双重保险隐藏轴线
          axisTick: { show: false }, // 隐藏刻度线
          axisLabel: { show: false },
          axisPointer: {
            show: false // 仅禁用 Y 轴指示线‌:ml-citation{ref="4,7" data="citationList"}
          }
        },
        series: [{
          name: '气泡',
          type: 'scatter',
          symbolSize: function (val) {
            const r = (val[2] / maxVal) * 50
            if (r < 30) {
              return 30
            } else if (r > 100) {
              return 100
            }
            return r;
          },
          label: {
            show: true,
            formatter: function(params) {           
              return params.data.data.name;
            },
            // fontSize: function(val) {
            //   console.log(val);
            //   const baseSize = 12; // 基准字号
            //   const currentSize = params.data.data.value;
            //   const scaleFactor = currentSize / maxVal;
            //   // return Math.max(baseSize * scaleFactor, 8)
            //   return 30;
            // },
            fontSize: 20,
            fontFamily: 'Xingkai, cursive',
            position: 'inside',
            color: '#fff'
          },
          data: this.generateNonOverlappingData(bubbleData).map(item => {
            return {
              value: [
                item.x,
                item.y,
                item.radius
              ],
              data: item.data
            }
          }),
          emphasis: {
            focus: 'series'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(120, 36, 50, 0.5)',
            shadowOffsetY: 5,
            color: '#a04c3b'
          }
        }]
      };

      chartInstance.setOption(option);
    }
  }
}
</script>
<style lang="scss" scoped>
.chart {
  border-left: 2px solid #95302e; 
}
</style>